import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'base_states.dart';

/// 列表数据加载基类
abstract class BaseListNotifier<T> extends StateNotifier<ListState<T>> {
  BaseListNotifier() : super(const ListState.initial());

  /// 每页数据量
  int get pageSize => 20;

  /// 自动加载数据
  bool get autoLoad => true;

  /// 加载数据抽象方法
  Future<PageResponse<T>> loadData(int page, int pageSize);

  /// 初始化加载
  Future<void> initLoad() async {
    if (!autoLoad || state.isLoading) return;

    state = const ListState.loading();

    try {
      final response = await loadData(1, pageSize);

      if (response.data.isEmpty) {
        state = state.copyWith(state: LoadState.empty, data: <T>[]);
      } else {
        state = ListState<T>.loaded(
          data: response.data,
          hasMore: response.hasMore,
          page: response.page,
        );
      }
    } catch (e) {
      state = ListState<T>.error(error: e.toString());
      onErrorOccurred(e);
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    if (state.isRefreshing) return;

    state = ListState.refreshing(data: state.data);

    try {
      final response = await loadData(1, pageSize);

      if (response.data.isEmpty) {
        state = state.copyWith(state: LoadState.empty, data: <T>[]);
      } else {
        state = ListState<T>.loaded(
          data: response.data,
          hasMore: response.hasMore,
          page: response.page,
        );
      }

      onRefreshSuccess();
    } catch (e) {
      state = state.copyWith(
        state: state.data?.isNotEmpty == true ? LoadState.loaded : LoadState.error,
        error: e.toString(),
        isRefreshing: false,
      );
      onErrorOccurred(e);
    }
  }

  /// 加载更多
  Future<void> loadMore() async {
    if (!state.hasMore || state.state == LoadState.loadMore || state.isLoading) {
      return;
    }

    final currentData = state.data ?? <T>[];
    final nextPage = state.page + 1;

    state = ListState<T>.loadingMore(
      data: currentData,
      page: nextPage,
    );

    try {
      final response = await loadData(nextPage, pageSize);

      final newData = <T>[...currentData, ...response.data];

      state = ListState<T>.loaded(
        data: newData,
        hasMore: response.hasMore,
        page: response.page,
      );

      onLoadMoreSuccess();
    } catch (e) {
      state = state.copyWith(
        state: LoadState.loaded,
        error: e.toString(),
        page: state.page - 1, // 回退页码
      );
      onErrorOccurred(e);
    }
  }

  /// 重试
  Future<void> retry() async {
    if (state.data?.isEmpty != false) {
      await initLoad();
    } else {
      await loadMore();
    }
  }

  /// 添加单个数据项
  void addItem(T item, {bool atTop = false}) {
    final currentData = List<T>.from(state.data ?? <T>[]);

    if (atTop) {
      currentData.insert(0, item);
    } else {
      currentData.add(item);
    }

    state = state.copyWith(
      state: LoadState.loaded,
      data: currentData,
      clearError: true,
    );
  }

  /// 删除数据项
  void removeItem(T item) {
    final currentData = List<T>.from(state.data ?? <T>[]);
    currentData.remove(item);

    state = state.copyWith(
      state: currentData.isEmpty ? LoadState.empty : LoadState.loaded,
      data: currentData,
      clearError: true,
    );
  }

  /// 更新数据项
  void updateItem(T oldItem, T newItem) {
    final currentData = List<T>.from(state.data ?? <T>[]);
    final index = currentData.indexOf(oldItem);

    if (index != -1) {
      currentData[index] = newItem;
      state = state.copyWith(
        state: LoadState.loaded,
        data: currentData,
        clearError: true,
      );
    }
  }

  /// 清空数据
  void clear() {
    state = const ListState.initial();
  }

  /// 错误回调
  void onErrorOccurred(dynamic error) {
    // 子类可以重写处理错误
  }

  /// 刷新成功回调
  void onRefreshSuccess() {
    // 子类可以重写
  }

  /// 加载更多成功回调
  void onLoadMoreSuccess() {
    // 子类可以重写
  }
}

/// 简单列表Notifier基类(不分页)
abstract class BaseSimpleListNotifier<T> extends StateNotifier<ListState<T>> {
  BaseSimpleListNotifier() : super(const ListState.initial());

  /// 加载数据抽象方法
  Future<List<T>> loadData();

  /// 初始化加载
  Future<void> initLoad() async {
    if (state.isLoading) return;

    state = const ListState.loading();

    try {
      final data = await loadData();

      if (data.isEmpty) {
        state = state.copyWith(state: LoadState.empty, data: <T>[]);
      } else {
        state = ListState<T>.loaded(data: data, hasMore: false);
      }
    } catch (e) {
      state = ListState<T>.error(error: e.toString());
      onErrorOccurred(e);
    }
  }

  /// 刷新数据
  Future<void> refresh() async {
    if (state.isRefreshing) return;

    state = ListState.refreshing(data: state.data);

    try {
      final data = await loadData();

      if (data.isEmpty) {
        state = state.copyWith(state: LoadState.empty, data: <T>[]);
      } else {
        state = ListState<T>.loaded(data: data, hasMore: false);
      }

      onRefreshSuccess();
    } catch (e) {
      state = state.copyWith(
        state: state.data?.isNotEmpty == true ? LoadState.loaded : LoadState.error,
        error: e.toString(),
        isRefreshing: false,
      );
      onErrorOccurred(e);
    }
  }

  /// 重试
  Future<void> retry() async {
    await initLoad();
  }

  /// 添加单个数据项
  void addItem(T item, {bool atTop = false}) {
    final currentData = List<T>.from(state.data ?? <T>[]);

    if (atTop) {
      currentData.insert(0, item);
    } else {
      currentData.add(item);
    }

    state = state.copyWith(
      state: LoadState.loaded,
      data: currentData,
      clearError: true,
    );
  }

  /// 删除数据项
  void removeItem(T item) {
    final currentData = List<T>.from(state.data ?? <T>[]);
    currentData.remove(item);

    state = state.copyWith(
      state: currentData.isEmpty ? LoadState.empty : LoadState.loaded,
      data: currentData,
      clearError: true,
    );
  }

  /// 更新数据项
  void updateItem(T oldItem, T newItem) {
    final currentData = List<T>.from(state.data ?? <T>[]);
    final index = currentData.indexOf(oldItem);

    if (index != -1) {
      currentData[index] = newItem;
      state = state.copyWith(
        state: LoadState.loaded,
        data: currentData,
        clearError: true,
      );
    }
  }

  /// 清空数据
  void clear() {
    state = const ListState.initial();
  }

  /// 错误回调
  void onErrorOccurred(dynamic error) {
    // 子类可以重写处理错误
  }

  /// 刷新成功回调
  void onRefreshSuccess() {
    // 子类可以重写
  }
}